//
//  LHIAPManager.m
//  LHIAPManager
//
//  Created by Apple on 2018/1/3.
//  Copyright © 2018年 youweidao. All rights reserved.
//

#import "LHIAPManager.h"
#import <StoreKit/StoreKit.h>
#import "NSString+nullStr.h"
#import "AppAlertTool.h"

@interface LHIAPManager()<SKPaymentTransactionObserver,SKProductsRequestDelegate>
@property(nonatomic,copy)NSString*productId;
@property(nonatomic,copy)NSString*payUrl;
@property(nonatomic,copy)successBlock sucBlock;
@property(nonatomic,copy)failureBlock faiBlock;
@end

@implementation LHIAPManager

#pragma mark -
#pragma mark - 单例
+(instancetype)sharedManager{
    
    static LHIAPManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[LHIAPManager alloc] init];
    });
    return manager;
}
#pragma mark -
#pragma mark - 初始化
-(instancetype)init{
    
    if (self=[super init]) {
        [self addTransactionObserver];
    }
    return self;
}
#pragma mark -
#pragma mark - 添加SKPaymentQueue的观察者
-(void)addTransactionObserver{
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}
#pragma mark -
#pragma mark - 移除SKPaymentQueue的观察者
-(void)removeTransactionObserver{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
#pragma mark -
#pragma mark - 移除SKPaymentQueue的观察者
-(void)dealloc{
    [self removeTransactionObserver];
}
#pragma mark -
#pragma mark -  开始购买
-(void)lh_startPurchaseWithProductID:(NSString* )productIdentifier andUrl:(LHIAPUrl)statusUrl andIAPSuccess:(successBlock)resultBlock andIAPfailure:(failureBlock)errorBlock{
    if (![SKPaymentQueue canMakePayments]) {
        return;
    }
    if ([NSString lh_isBlankString:productIdentifier]) {
        return;
    }
    if (statusUrl==LHIAPUrlTest) {
        self.payUrl=@"https://sandbox.itunes.apple.com/verifyReceipt";
    }else{
        self.payUrl=@"https://buy.itunes.apple.com/verifyReceipt";
    }
    self.productId=productIdentifier;
    NSArray *product = [[NSArray alloc] initWithObjects:productIdentifier,nil];
    NSSet *nsset = [NSSet setWithArray:product];
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
    request.delegate = self;
    [request start];
    self.sucBlock = resultBlock;
    self.faiBlock = errorBlock;
}

- (void)requestDidFinish:(SKRequest *)request{
//    NSLog(@"请求结束");
    
}
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
//    NSLog(@"请求失败");
}
#pragma mark -
#pragma mark -  SKProductsRequestDelegate
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    NSLog(@"收到支付响应=%@",response.products);
    NSArray*productArr=response.products;
    /** 1.验证返回的数据大于0 */
    if (productArr.count==0) {
        [AppAlertTool lh_alterViewWithTitle:@"提示" AndContentString:@"当前商品数目为0,无法购买" AndComfirmBtnTitle:@"确定" AndCancelTitle:@"取消" AndShow:[UIApplication sharedApplication].keyWindow.rootViewController AndComfirmBlock:^{
        
        } AndCancelBlock:^{
            
        }];
        return;
    }
    /** 2.验证传进来的productIdentifier是否是无效的产品ID */
    for (NSString* idStr in response.invalidProductIdentifiers) {
        if ([self.productId isEqualToString:idStr]) {
            [AppAlertTool lh_alterViewWithTitle:@"提示" AndContentString:@"当前商品ID无效,无法购买" AndComfirmBtnTitle:@"确定" AndCancelTitle:@"取消" AndShow:[UIApplication sharedApplication].keyWindow.rootViewController AndComfirmBlock:^{
                
            } AndCancelBlock:^{
                
            }];
            return;
        }
    }
    /** 3.遍历响应数组，开始发起内购 */
    SKProduct *p = nil;
    for (SKProduct *pro in productArr) {
        NSLog(@"产品描述：%@", [pro description]);
        NSLog(@"产品本地化标题：%@", [pro localizedTitle]);
        NSLog(@"产品本地化描述：%@", [pro localizedDescription]);
        NSLog(@"产品价格：%@", [pro price]);
        NSLog(@"产品ID：%@", [pro productIdentifier]);
        if([pro.productIdentifier isEqualToString:self.productId]){
            p=pro;
        }
    }
    SKPayment *payment = [SKPayment paymentWithProduct:p];
    [[SKPaymentQueue defaultQueue]  addPayment:payment];
}
#pragma mark -
#pragma mark -  SKPaymentTransactionObserver
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions{
    for (SKPaymentTransaction* trans in transactions) {
        switch (trans.transactionState) {
                /**
                 SKPaymentTransactionStatePurchasing,
                 SKPaymentTransactionStatePurchased,
                 SKPaymentTransactionStateFailed,
                 SKPaymentTransactionStateRestored,
                 SKPaymentTransactionStateDeferred NS_ENUM_AVAILABLE_IOS(8_0)
                 */
            case SKPaymentTransactionStatePurchasing:{
                //用户正在将事务添加至服务队列Transaction is being added to the server queue
            }
                break;
            case SKPaymentTransactionStatePurchased:{
                [self verifyPurchaseWithPaymentTransaction];
                //用户已经付费完成购买
                [[SKPaymentQueue defaultQueue] finishTransaction:trans];
            }
                break;
            case SKPaymentTransactionStateFailed:{
                //交易取消或者失败的状态
                
                [AppAlertTool lh_alterViewWithTitle:@"提示" AndContentString:trans.error.localizedDescription AndComfirmBtnTitle:@"确定" AndCancelTitle:@"取消" AndShow:[UIApplication sharedApplication].keyWindow.rootViewController AndComfirmBlock:^{
                    
                } AndCancelBlock:^{
                    
                }];
                [[SKPaymentQueue defaultQueue] finishTransaction:trans];
            }
                break;
            case SKPaymentTransactionStateRestored:{
                //用户恢复购买。Transaction was restored from user's purchase history
            }
                break;
            case SKPaymentTransactionStateDeferred:{
                //等待外部操作的状态
            }
                break;
            default:
                break;
        }
    }
}

#pragma mark -
#pragma mark - 苹果服务器返回结果
- (void)verifyPurchaseWithPaymentTransaction{
    NSLog(@"开始验证==========");
    //1.获取苹果服务器的地址
    NSString *url = self.payUrl;
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    //2.创建URL请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    request.timeoutInterval=20;
    [request setHTTPMethod:@"POST"];
    
    //3.添加请求体
    NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
    NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", receiptString];
    NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = bodyData;
    
    //4.开始请求
    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error && data) {
             NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"苹果返回结果=%@",dic);
            if (self.sucBlock) {
                self.sucBlock(dic);
//                NSLog(@"苹果购买成功");
            }
        }else{
            if (self.faiBlock) {
                self.faiBlock(error);
            }
        }
    }];
    [task resume];
    
}
@end
